<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2020/1/7
 * Time: 14:07
 */
namespace app\admin\controller;
use app\admin\model\AdminActionLogModel;
use app\admin\validate\ConfigValidate;
use app\common\controller\BackendController;
use app\admin\model\Config as ConfigModel;
use think\Exception;
use think\facade\Db;
use think\facade\View;
use app\admin\model\Recycle;
use util\ConfigUtil;

class Config extends BackendController
{
    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        if($this->request->isAjax()){
            $this->model = ConfigModel::instance();
            list($where,$sort,$order,$page,$limit) = $this->model->buildParams($this->request);
            $total = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page,$limit)
                ->order($sort,$order)
                ->append(['type_text','group_text'])
                ->select();
            $this->success('查询成功','',['list'=>$list,'total'=>$total]);
        }
        $this->getConfigCommonData();
        return view();
    }
    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setting(){
        if($this->request->isPost()){
            $data = $this->request->param('setting');
            try {
                Db::transaction(function ()use ($data){
                    foreach ($data as $name => $value) {
                        if(!ConfigModel::update(['value' => $value], ['name' => $name])){
                            throw new Exception('编辑失败，name:'.$name);
                        }
                    }
                });
                AdminActionLogModel::logAdd('编辑系统设置','编辑的系统设置name:'.json_encode(array_keys($data)));
                $this->success('编辑成功');
            }catch (Exception $e){
                $this->error('编辑失败:'.$e->getMessage());
            }
        }
        $this->getConfigCommonData();
        $this->model = ConfigModel::instance();
        $config_list = $this->model->select();
        View::assign('list',$config_list);
        return view();
    }

    public function add(){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            if(!ConfigValidate::instance()->scene('add')->check($data)){
                $this->error(ConfigValidate::instance()->getError());
            }
            $res = ConfigModel::create($data,['name','title','type','group','extra','sort','describe','value','create_time']);
            if(!$res){
                $this->error('添加失败');
            }
            AdminActionLogModel::logAdd('添加设置','设置名称:'.$data['title']);
            $this->success('添加成功');
        }
        $this->getConfigCommonData();
        return view('edit');
    }
    /**
     * @param null $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id = null){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            if(!ConfigValidate::instance()->scene('edit')->check($data)){
                $this->error(ConfigValidate::instance()->getError());
            }
            $res = ConfigModel::update($data,[],['id','name','title','type','group','extra','sort','describe','value','update_time']);
            if(!$res){
                $this->error('更新失败');
            }
            AdminActionLogModel::logAdd('更新设置','设置id:'.$data['id']);
            $this->success('更新成功');
        }
        if(!$id){
            $this->error('id不能为空!');
        }
        $this->getConfigCommonData();
        $info = ConfigModel::find($id);
        View::assign('info',$info);
        return view();
    }
    /**
     * 获取通用数据
     */
    protected function getConfigCommonData()
    {
        $config_group_list = ConfigUtil::instance()->parse_config_array(config('config.config_group_list'));
        $config_type_list  = ConfigUtil::instance()->parse_config_array(config('config.config_type_list'));
        View::assign('config_group_list', $config_group_list);
        View::assign('config_type_list' , $config_type_list);
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(){
        $ids = $this->request->param('ids/a');
        if(empty($ids)){
            $this->error('删除的数据不能为空！');
        }
        $config_list = ConfigModel::select($ids);
        $del_arr = [];
        foreach ($config_list as $config){
            $tmp = [
                'object_id'=>$config['id'],
                'table_name'=>'config',
                'name'=>$config['title'],
                'admin_id'=>$this->auth->id
            ];
            $del_arr[] = $tmp;
        }
        try {
            Db::transaction(function () use ($ids, $del_arr) {
                $res = ConfigModel::destroy($ids);
                if (!$res) {
                    throw new Exception('删除失败！', 401);
                }
                if (!Recycle::instance()->saveAll($del_arr)) {
                    throw new Exception('删除失败！', 402);
                }
            });
            AdminActionLogModel::logAdd('删除设置','删除ids:'.json_encode($ids));
            $this->success('删除成功');
        }catch (Exception $e){
            $this->error('删除失败');
        }
    }
}